package com.yun.algorithmproblem.leetcode;

public class Leetcode1254 {
    public int closedIsland(int[][] grid) {
        int row = grid.length;
        int column = grid[0].length;
        int count = 0;
        boolean[][] isMark = new boolean[row][column];
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < column; j++) {
                if (grid[i][j] == 0 && !isMark[i][j]) {
                    if (dfs(grid, isMark, i, j)) {
                        count++;
                    }
                }
            }
        }
        return count;
    }

    private boolean dfs(int[][] grid, boolean[][] isMark, int i, int j) {
        if (i < 0 || j < 0 || i > grid.length - 1 || j > grid[0].length - 1) {
            return false;
        }
        if (grid[i][j] == 1 || isMark[i][j]) {
            return true;
        }
        isMark[i][j] = true;
        boolean up = dfs(grid, isMark, i, j + 1);
        boolean down = dfs(grid, isMark, i, j - 1);
        boolean left = dfs(grid, isMark, i - 1, j);
        boolean right = dfs(grid, isMark, i + 1, j);
        return up&down&left&right;
    }

    public static void main(String[] args) {
        int[][] grid = {{0, 0, 1, 1, 0, 1, 0, 0, 1, 0},
                {1, 1, 0, 1, 1, 0, 1, 1, 1, 0},
                {1, 0, 1, 1, 1, 0, 0, 1, 1, 0},
                {0, 1, 1, 0, 0, 0, 0, 1, 0, 1},
                {0, 0, 0, 0, 0, 0, 1, 1, 1, 0},
                {0, 1, 0, 1, 0, 1, 0, 1, 1, 1},
                {1, 0, 1, 0, 1, 1, 0, 0, 0, 1},
                {1, 1, 1, 1, 1, 1, 0, 0, 0, 0},
                {1, 1, 1, 0, 0, 1, 0, 1, 0, 1},
                {1, 1, 1, 0, 1, 1, 0, 1, 1, 0}};

    }
}
